package com.py.credit.service.impl;

import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import com.py.credit.common.logs.ExceptionLogger;
import com.py.credit.dao.RuleBindingDao;
import com.py.credit.dao.RuleCheckingDao;
import com.py.credit.entity.common.InspectRule;
import com.py.credit.service.XypjInspectDataService;
import com.py.credit.utils.DateUtil;

/**
 * @Company: WWW.xypy.com.cn
 * @ClassName XypjInspectDataServiceImpl
 * @Description: 信用评价校验代码
 * @Params: Test
 * @Author: YaoS
 * @Create: 2018-11-02 10:09
 **/
@Service
public class XypjInspectDataServiceImpl implements XypjInspectDataService {
	private final String TIME = "timestamp";
	@Autowired
	private RuleCheckingDao ruleCheckingDao;

	@Autowired
	private RuleBindingDao ruleBindingDao;

	/**
	 * 信用评价校验
	 *
	 * @param value
	 *            数据值
	 * @param tableId
	 *            表id
	 * @param type
	 *            数据类型
	 * @param code
	 *            校验code
	 * @return Map
	 * @author YaoS
	 * @date 10:03 18/11/2
	 **/
	@Override
	public Map<String, Object> xypjCkeck(String value, String tableId, String type, String code) {
		Map<String, Object> errorCol = new HashMap<>();
		// 获取当前版本
		int editionId = ruleBindingDao.selectCurrentContentVersion();
		// 获取当前字段规则
		List<InspectRule> list = ruleCheckingDao.selectColumnRule(code, editionId, Integer.valueOf(tableId));
		StringBuilder sb = new StringBuilder(200);
		Class<?> c = null;
		Method m = null;
		// 整条数据所有的字段校验结果 true为通过
		boolean totalValidate = true;
		if (TIME.equals(type)) {
			value = String.format(value, DateUtil.YYYY__MM__DD);
		}
		if (!CollectionUtils.isEmpty(list)) {
			for (InspectRule rule : list) {
				// 默认校验通过
				boolean validate = true;
				try {
					c = Class.forName(rule.getRulePackage());
					m = c.getMethod(rule.getRuleMethod(), String.class, String.class);
					validate = (boolean) m.invoke(c.newInstance(), value, rule.getExtend());
				} catch (Exception e) {
					ExceptionLogger.error("XypjInspectDataServiceImpl#colunmCheck", "字段规则校验异常！ERROR：" + e.getMessage(),
							e);
				}
				// 校验未通过
				if (!validate) {
					// 单个字段校验未通过就为未通过
					totalValidate = false;
					String reason = code + ":" + rule.getRuleDesc() + ";";
					// 拼接到所有异常
					sb.append(reason);
				}
			}
		}
		errorCol.put("status", totalValidate);
		errorCol.put("msg", sb);
		return errorCol;
	}

}
